package util;

import com.sun.media.imageio.plugins.tiff.TIFFTag;  
import com.sun.media.jai.codec.TIFFEncodeParam;  
import com.sun.media.jai.codec.TIFFField;  
import com.sun.media.jai.codecimpl.TIFFImageEncoder;  
import component.fileupload.util.BcsUtil;

import java.awt.image.RenderedImage;  
import java.io.File;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.util.Calendar;
import java.util.GregorianCalendar;
 
public class TiffOutput {  
    public static File getTiffFile(RenderedImage image, String outputFilePath, int dpi) throws Exception {  
    	File outputFile = null;
        try {  
            if (image != null) {  
                TIFFEncodeParam param = new TIFFEncodeParam();  
                param.setCompression(TIFFEncodeParam.COMPRESSION_NONE);  
                TIFFField[] extras = new TIFFField[2];  
                extras[0] = new TIFFField(282, TIFFTag.TIFF_RATIONAL, 1, (Object) new long[][]{{(long) dpi, 1}, {0, 0}});  
                extras[1] = new TIFFField(283, TIFFTag.TIFF_RATIONAL, 1, (Object) new long[][]{{(long) dpi, 1}, {0, 0}});  
                param.setExtraFields(extras);  
                
                if(outputFilePath == null || "".equals(outputFilePath)) {
                	outputFile = createTempFile(); 
                } else {
                	outputFile = new File(outputFilePath);  
                }
                outputFile.createNewFile();  
                FileOutputStream outputStream = new FileOutputStream(outputFile);  
                TIFFImageEncoder encoder = new TIFFImageEncoder(outputStream, param);  
                encoder.encode(image);  
                outputStream.close();  
            }  
        } catch (IOException ex) {  
            ex.printStackTrace();  
            throw new Exception(ex);
        }  
        return outputFile;
    }  
    
    public static String upload(RenderedImage image, int dpi) throws Exception {
    	GregorianCalendar now = new GregorianCalendar();
    	String fileName = String.valueOf(now.getTimeInMillis());
		String saveFilePath = "/ad_case/" + now.get(Calendar.YEAR) + "/" + (now.get(Calendar.MONTH) < 9 ? "0" + (now.get(Calendar.MONTH) + 1) : "" + (now.get(Calendar.MONTH) + 1));
		saveFilePath += "/" + fileName;
		
		File file = getTiffFile(image, null, dpi);
    	return BcsUtil.upload(file, saveFilePath);
    }
    
    private static File createTempFile() throws IOException {
    	GregorianCalendar now = new GregorianCalendar();
    	String fileName = String.valueOf(now.getTimeInMillis());
		File file = File.createTempFile(fileName, ".tif");
		file.deleteOnExit();
		return file;
	}
    
}  
